// app/login/page.tsx
'use client';
import { useState } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';

export default function Login() {
  const [email, setEmail] = useState('123456');
  const [password, setPassword] = useState('123456');
  const [error, setError] = useState('');
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') || '/user';

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    const result = await signIn('credentials', {
      redirect: false,
      email,
      password,
    });

    if (result?.error) {
      setError(result.error);
    } else {
      // console.log('success', result);
      router.push(callbackUrl);
    }
  };

  return (
    <div className='mx-auto max-w-md p-4'>
      <h1 className='mb-4 text-2xl'>登录</h1>
      <form onSubmit={handleSubmit} className='space-y-4'>
        <div>
          <label htmlFor='email' className='block'>
            邮箱
          </label>
          <input
            id='email'
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className='w-full rounded border p-2'
            required
          />
        </div>
        <div>
          <label htmlFor='password' className='block'>
            密码
          </label>
          <input
            id='password'
            type='password'
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className='w-full rounded border p-2'
            required
          />
        </div>
        {error && <p className='text-red-500'>{error}</p>}
        <button
          type='submit'
          className='w-full rounded bg-blue-500 p-2 text-white'
        >
          登录
        </button>
      </form>
    </div>
  );
}
